package com.njwb.day15.zqzb.jdbc;

import java.sql.*;

public class QueryStudentsTest {
    public static void main(String[] args) {
        //构建连接对象
        Connection connection= null ;
        //命令器
        Statement statement= null ;
        //结果集
        ResultSet rs = null ;


        try {
            //1、加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","root");
            //3、创建命令器
            statement = connection.createStatement();
            //4、准备待执行的sql语句
            String sql = "select sid,sname,age,address from tb_student";
            //5.执行sql语句,返回结果集对象，并读取结果集
            rs = statement.executeQuery(sql);
            //读取结果集
            while(rs.next()) {
                int sid = rs.getInt("sid");
                String sname=rs.getString("sname");
                int age = rs.getInt("age");
                String address = rs.getString("address");
                System.out.println("编号："+sid+",姓名："+sname+",年龄："+age+",地址："+address);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6、关闭资源 （倒着关闭）
            if(rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(statement!=null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
